<template>
  <div>
    <div class="toolbar">
      <el-select v-model="status" placeholder="状态" style="width: 160px" clearable>
        <el-option label="提交" value="SUBMITTED" />
        <el-option label="教师审核" value="TEACHER_REVIEW" />
        <el-option label="教务审批" value="ACADEMIC_APPROVAL" />
        <el-option label="已处理" value="RESOLVED" />
        <el-option label="已拒绝" value="REJECTED" />
      </el-select>
      <el-select v-model="studentId" placeholder="学生" filterable clearable style="width: 220px">
        <el-option v-for="s in studentOptions" :key="s.id" :label="`${s.studentNo} - ${s.name}`" :value="s.id" />
      </el-select>
      <el-select v-model="offeringId" placeholder="开课" filterable clearable style="width: 240px">
        <el-option v-for="o in offeringOptions" :key="o.id" :label="`开课#${o.id} 课程${o.courseId} 班级${o.classId} 学期${o.termId}`" :value="o.id" />
      </el-select>
      <el-button type="primary" @click="load">查询申诉</el-button>
      <el-button type="success" @click="openCreate">新增申诉</el-button>
    </div>

    <el-table :data="items" stripe style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="studentId" label="学生ID" width="110" />
      <el-table-column prop="offeringId" label="开课ID" width="110" />
      <el-table-column prop="itemId" label="成绩项ID" width="110" />
      <el-table-column prop="reason" label="申诉原因" />
      <el-table-column prop="status" label="状态" width="160" />
      <el-table-column prop="result" label="处理结果" />
      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button size="small" @click="openEdit(row)">编辑</el-button>
          <el-popconfirm title="确认删除该申诉？" @confirm="doDelete(row.id)">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="editing ? '编辑申诉' : '新增申诉'" width="680">
      <el-form :model="form" label-width="120px">
        <el-form-item label="学生">
          <el-select v-model="form.studentId" placeholder="选择学生" filterable style="width: 240px">
            <el-option v-for="s in studentOptions" :key="s.id" :label="`${s.studentNo} - ${s.name}`" :value="s.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="开课">
          <el-select v-model="form.offeringId" placeholder="选择开课" filterable style="width: 240px">
            <el-option v-for="o in offeringOptions" :key="o.id" :label="`开课#${o.id} 课程${o.courseId} 班级${o.classId} 学期${o.termId}`" :value="o.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="成绩项">
          <el-select v-model="form.itemId" placeholder="选择成绩项" filterable style="width: 240px">
            <el-option v-for="it in itemOptions" :key="it.id" :label="`${it.name}（满分${it.maxScore}，权重${it.weight}%）`" :value="it.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="申诉原因"><el-input v-model="form.reason" type="textarea" /></el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="选择">
            <el-option label="提交" value="SUBMITTED" />
            <el-option label="教师审核" value="TEACHER_REVIEW" />
            <el-option label="教务审批" value="ACADEMIC_APPROVAL" />
            <el-option label="已处理" value="RESOLVED" />
            <el-option label="已拒绝" value="REJECTED" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理结果"><el-input v-model="form.result" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { listAppeals, createAppeal, updateAppeal, deleteAppeal, type Appeal } from '@/api/grades/appeals'
import { listStudents, type Student } from '@/api/grades/students'
import { listOfferings, type CourseOffering } from '@/api/grades/offerings'
import { listScoreItems, type ScoreItem } from '@/api/grades/scoreItems'

const loading = ref(false)
const items = ref<Appeal[]>([])
const status = ref<string | undefined>(undefined)
const studentId = ref<number | undefined>(undefined)
const offeringId = ref<number | undefined>(undefined)

const dialogVisible = ref(false)
const editing = ref(false)
const form = ref<Appeal>({ status: 'SUBMITTED' })
const studentOptions = ref<Student[]>([])
const offeringOptions = ref<CourseOffering[]>([])
const itemOptions = ref<ScoreItem[]>([])

async function load() {
  loading.value = true
  try {
    items.value = await listAppeals({ status: status.value, offeringId: offeringId.value, studentId: studentId.value })
  } finally {
    loading.value = false
  }
}

function openCreate() {
  editing.value = false
  form.value = { status: 'SUBMITTED', studentId: studentId.value, offeringId: offeringId.value }
  dialogVisible.value = true
}

function openEdit(row: Appeal) {
  editing.value = true
  form.value = { ...row }
  dialogVisible.value = true
  loadItemOptionsFor(form.value.offeringId)
}

async function submit() {
  try {
    if (editing.value && form.value.id) {
      await updateAppeal(form.value.id, form.value)
      ElMessage.success('更新成功')
    } else {
      await createAppeal(form.value)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    await load()
  } catch (e: any) {
    ElMessage.error(e?.message || '操作失败')
  }
}

async function doDelete(id?: number) {
  if (!id) return
  try {
    await deleteAppeal(id)
    ElMessage.success('已删除')
    await load()
  } catch (e: any) {
    ElMessage.error(e?.message || '删除失败')
  }
}

async function loadStudentOptions() {
  try {
    const res = await listStudents({ offset: 0, limit: 1000 })
    studentOptions.value = res.items
  } catch {}
}

async function loadOfferingOptions() {
  try {
    offeringOptions.value = await listOfferings({})
  } catch {}
}

async function loadItemOptionsFor(offId?: number) {
  try {
    if (!offId) { itemOptions.value = []; return }
    itemOptions.value = await listScoreItems({ offeringId: offId })
  } catch {}
}

watch(() => form.value.offeringId, (val) => {
  loadItemOptionsFor(val)
})

onMounted(() => {
  loadStudentOptions()
  loadOfferingOptions()
})
</script>

<style scoped>
.toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  align-items: center;
}
</style>